<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.namespace" placeholder="Namespace (留空获取所有)" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.jobName" placeholder="Job Name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加 Job
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="info" icon="el-icon-refresh" @click="getList">
        刷新
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="命名空间" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nameSpace || 'default' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Job 名称" min-width="180px">
        <template slot-scope="{row}">
          <span class="job-name">{{ row.jobName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="容器" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.containerName || 'N/A' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="镜像" min-width="200px">
        <template slot-scope="{row}">
          <el-tooltip effect="dark" :content="row.containerImage" placement="top">
            <span class="text-ellipsis">{{ row.containerImage || 'N/A' }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="命令" min-width="200px">
        <template slot-scope="{row}">
          <el-tooltip v-if="row.commandArgs" effect="dark" :content="row.commandArgs" placement="top">
            <span class="text-ellipsis">{{ row.commandArgs }}</span>
          </el-tooltip>
          <span v-else>N/A</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="getStatusType(row)" size="small">
            {{ getJobStatus(row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="运行状态" width="120px" align="center">
        <template slot-scope="{row}">
          <div class="pod-status">
            <span v-if="row.podsStatuses" class="status-item">
              <i v-if="getActivePods(row) > 0" class="el-icon-loading" />
              活跃: {{ getActivePods(row) }}
            </span>
            <span v-else>N/A</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" width="170px" align="center">
        <template slot-scope="{row}">
          <span>{{ formatTime(row.start_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" width="170px" align="center">
        <template slot-scope="{row}">
          <span>{{ formatTime(row.end_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleDetail(row)">
            详情
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <div v-if="!listLoading && list.length === 0" class="empty-container">
      <el-empty description="暂无 Job 数据">
        <el-button type="primary" @click="handleCreate">创建 Job</el-button>
      </el-empty>
    </div>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 创建 Job 对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="600px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 500px; margin-left:50px;">
        <el-form-item label="Job 名称" prop="jobName">
          <el-input v-model="temp.jobName" placeholder="输入 Job 名称" />
        </el-form-item>
        <el-form-item label="命名空间" prop="nameSpace">
          <el-input v-model="temp.nameSpace" placeholder="输入命名空间，如：default" />
        </el-form-item>
        <el-form-item label="容器名称" prop="containerName">
          <el-input v-model="temp.containerName" placeholder="输入容器名称" />
        </el-form-item>
        <el-form-item label="容器镜像" prop="containerImage">
          <el-input v-model="temp.containerImage" placeholder="输入容器镜像，如：busybox:latest" />
        </el-form-item>
        <el-form-item label="执行命令" prop="command">
          <el-input
            v-model="temp.command"
            type="textarea"
            :rows="3"
            placeholder="输入要执行的命令，例如：echo &quot;Hello Kubernetes Job&quot;"
          />
          <div class="form-tips">提示：命令将直接在容器中执行</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- Job 详情对话框 -->
    <el-dialog :visible.sync="dialogDetailVisible" title="Job 详情" width="800px">
      <el-descriptions v-if="currentJobDetail.jobName" :column="2" border>
        <el-descriptions-item label="Job 名称">{{ currentJobDetail.jobName }}</el-descriptions-item>
        <el-descriptions-item label="命名空间">{{ currentJobDetail.nameSpace }}</el-descriptions-item>
        <el-descriptions-item label="容器名称">{{ currentJobDetail.containerName }}</el-descriptions-item>
        <el-descriptions-item label="容器镜像">{{ currentJobDetail.containerImage }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentJobDetail)">
            {{ getJobStatus(currentJobDetail) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="命令" :span="2">
          <pre style="margin: 0; white-space: pre-wrap; background: #f5f7fa; padding: 10px; border-radius: 4px;">{{ currentJobDetail.commandArgs || 'N/A' }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ formatTime(currentJobDetail.start_time) }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ formatTime(currentJobDetail.end_time) }}</el-descriptions-item>
        <el-descriptions-item label="Pod 状态" :span="2">
          <div v-if="currentJobDetail.podsStatuses">
            <div class="status-detail">
              <span class="status-item">活跃: {{ getActivePods(currentJobDetail) }}</span>
              <span class="status-item">成功: {{ getSucceededPods(currentJobDetail) }}</span>
              <span class="status-item">失败: {{ getFailedPods(currentJobDetail) }}</span>
            </div>
          </div>
          <span v-else>N/A</span>
        </el-descriptions-item>
        <el-descriptions-item label="标签" :span="2">
          <pre style="margin: 0; white-space: pre-wrap; background: #f5f7fa; padding: 10px; border-radius: 4px;">{{ formatLabels(currentJobDetail.labels) }}</pre>
        </el-descriptions-item>
      </el-descriptions>
      <div v-else>
        <p>加载 Job 详情中...</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogDetailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GetJobList, CreateJob, DeleteJob, GetJobDetail } from '@/api/k8sJobs'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'

export default {
  name: 'JobTable',
  components: { Pagination },
  directives: { waves },

  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        namespace: '',
        jobName: '',
        sort: '+id'
      },
      temp: {
        jobName: 'test-job-' + Date.now(),
        nameSpace: 'default',
        containerName: 'app-container',
        containerImage: 'busybox:latest',
        command: 'echo "Hello Kubernetes Job"'
      },
      dialogFormVisible: false,
      dialogDetailVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑 Job',
        create: '创建 Job'
      },
      currentJobDetail: {},
      rules: {
        jobName: [{ required: true, message: 'Job 名称是必需的', trigger: 'blur' }],
        nameSpace: [{ required: true, message: '命名空间是必需的', trigger: 'blur' }],
        containerName: [{ required: true, message: '容器名称是必需的', trigger: 'blur' }],
        containerImage: [{ required: true, message: '容器镜像是必需的', trigger: 'blur' }],
        command: [{ required: true, message: '执行命令是必需的', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true

      try {
        const namespace = this.listQuery.namespace || ''
        const response = await GetJobList(namespace)

        console.log('API响应数据:', response) // 调试日志

        // 检查响应结构
        if (response && response.jobList) {
          let jobList = response.jobList

          // 根据 jobName 过滤
          if (this.listQuery.jobName) {
            jobList = jobList.filter(job => {
              const name = job.jobName || ''
              return name.toLowerCase().includes(this.listQuery.jobName.toLowerCase())
            })
          }

          this.list = jobList
          this.total = jobList.length

          console.log('处理后列表数据:', this.list) // 调试日志
        } else {
          console.warn('响应数据格式不正确:', response)
          this.list = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取 Job 列表失败:', error)

        let errorMessage = '获取 Job 列表失败'
        if (error.response) {
          errorMessage = `服务器错误: ${error.response.status} - ${error.response.data?.message || error.response.data || '未知错误'}`
        } else if (error.request) {
          errorMessage = '无法连接到服务器，请检查后端服务是否运行'
        } else {
          errorMessage = `请求错误: ${error.message}`
        }

        this.$message({
          message: errorMessage,
          type: 'error',
          duration: 5000
        })

        this.list = []
        this.total = 0
      } finally {
        this.listLoading = false
      }
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    resetTemp() {
      this.temp = {
        jobName: 'test-job-' + Date.now(),
        nameSpace: 'default',
        containerName: 'app-container',
        containerImage: 'busybox:latest',
        command: 'echo "Hello Kubernetes Job"'
      }
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const jobData = {
            jobName: this.temp.jobName,
            nameSpace: this.temp.nameSpace,
            containerName: this.temp.containerName,
            containerImage: this.temp.containerImage,
            command: this.temp.command
          }

          CreateJob(jobData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: 'Job 创建成功',
              type: 'success',
              duration: 2000
            })
            // 延迟一下再获取列表，给 K8s 一些处理时间
            setTimeout(() => {
              this.getList()
            }, 2000)
          }).catch(error => {
            console.error('创建 Job 失败:', error)
            let errorMessage = '创建 Job 失败'
            if (error.response && error.response.data) {
              errorMessage = error.response.data.message || error.response.data.error || errorMessage
            }
            this.$notify({
              title: '错误',
              message: errorMessage,
              type: 'error',
              duration: 5000
            })
          })
        }
      })
    },

    handleDetail(row) {
      const namespace = row.nameSpace || 'default'
      const jobName = row.jobName

      GetJobDetail(namespace, jobName).then(response => {
        this.currentJobDetail = response
        this.dialogDetailVisible = true
      }).catch(error => {
        console.error('获取 Job 详情失败:', error)
        this.currentJobDetail = row
        this.dialogDetailVisible = true
        this.$message({
          message: '获取 Job 详情失败',
          type: 'error'
        })
      })
    },

    handleDelete(row) {
      const namespace = row.nameSpace || 'default'
      const jobName = row.jobName

      this.$confirm(`确定要删除 Job "${jobName}" 吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        DeleteJob(namespace, jobName).then(response => {
          // 根据后端返回判断删除是否成功
          if (response.message === 'success' || response.messge === 'success') {
            this.getList()
            this.$message({
              message: `Job ${jobName} 删除成功`,
              type: 'success'
            })
          } else {
            throw new Error('删除失败')
          }
        }).catch(error => {
          console.error('删除 Job 失败:', error)
          this.listLoading = false
          let errorMessage = `删除 Job ${jobName} 失败`
          if (error.response && error.response.data) {
            errorMessage = error.response.data.message || errorMessage
          }
          this.$message({
            message: errorMessage,
            type: 'error'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },

    getJobStatus(job) {
      // 根据 end_time 是否为空来判断状态
      if (job.end_time && job.end_time.trim() !== '') {
        return '已完成'
      } else if (job.start_time && job.start_time.trim() !== '') {
        return '运行中'
      } else {
        return '等待中'
      }
    },

    getStatusType(job) {
      const status = this.getJobStatus(job)
      const statusMap = {
        '已完成': 'success',
        '运行中': 'primary',
        '等待中': 'warning',
        '失败': 'danger'
      }
      return statusMap[status] || 'info'
    },

    // 从 podsStatuses 中提取活跃 Pod 数量
    getActivePods(job) {
      if (!job.podsStatuses) return 0
      const match = job.podsStatuses.match(/活跃:\s*(\d+)/)
      return match ? parseInt(match[1]) : 0
    },

    // 从 podsStatuses 中提取成功 Pod 数量
    getSucceededPods(job) {
      if (!job.podsStatuses) return 0
      const match = job.podsStatuses.match(/成功:\s*(\d+)/)
      return match ? parseInt(match[1]) : 0
    },

    // 从 podsStatuses 中提取失败 Pod 数量
    getFailedPods(job) {
      if (!job.podsStatuses) return 0
      const match = job.podsStatuses.match(/失败:\s*(\d+)/)
      return match ? parseInt(match[1]) : 0
    },

    formatTime(timestamp) {
      if (!timestamp || timestamp.trim() === '') return 'N/A'

      // 尝试使用 parseTime 格式化
      try {
        const formatted = parseTime(timestamp)
        if (formatted) {
          return formatted
        }
      } catch (e) {
        console.warn('时间格式化失败:', e)
      }

      // 如果 parseTime 无法解析，则尝试提取日期和时间部分
      // 格式: "2025-10-05 22:24:20 +0800 CST"
      const match = timestamp.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/)
      return match ? match[1] : timestamp
    },

    formatLabels(labels) {
      if (!labels) return 'N/A'
      // 将 "map[key:value key2:value2]" 格式转换为更易读的格式
      try {
        return labels.replace(/^map\[|\]$/g, '').replace(/\s+/g, '\n')
      } catch (e) {
        return labels
      }
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.text-ellipsis {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: bottom;
}

.empty-container {
  text-align: center;
  padding: 40px 0;
}

.form-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.job-name {
  font-weight: 500;
}

.pod-status {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.status-item {
  display: inline-block;
  margin: 2px 0;
  font-size: 12px;
}

.status-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.status-detail .status-item {
  font-size: 14px;
}
</style>
